<template>
  <div class="container">
    <div class="top">
      <van-search
        v-model="searchValue"
        placeholder="请输入搜索关键词"
        shape="round"
        show-action
        clearable
        @cancel="cancelClick"
      />
      <van-tabs v-model:active="active">
        <template v-for="(item1, key, index) in cityData" :key="index">
          <van-tab :title="item1.title" :name="key"></van-tab>
        </template>
      </van-tabs>
    </div>
    <!-- 方法一 -->
    <!-- <scroll-view class="content">
      <cityGroup :currentGroup></cityGroup>
    </scroll-view> -->
    <!-- 方法二 -->
    <keep-alive>
      <scroll-view class="content">
        <cityGroup
          @sendmyson="sendmyson"
          v-for="(item1, key, index) in cityData"
          :key="key"
          :currentGroup
          v-show="active === key"
        ></cityGroup>
      </scroll-view>
    </keep-alive>
  </div>
</template>

<script setup>
import { useRouter } from 'vue-router'
import { ref, onMounted, watch, computed } from 'vue'
import useCityStore from '@/stores/modules/city'
import { storeToRefs } from 'pinia'
import cityGroup from './city-group.vue'

const cityStore = useCityStore()

onMounted(() => {
  getAllCity()
})

const router = useRouter()
const searchValue = ref('')
const active = ref(0)
const cityData = ref([]) // 初始化为空数组

const cancelClick = () => {
  router.back()
}

const getAllCity = async () => {
  await cityStore.fetchCityList() // 确保异步操作完成
  const { cityList } = storeToRefs(cityStore)
  console.log('1111', cityList.value) // 打印 cityList 的实际值
  cityData.value = cityList.value // 将实际值赋给 cityData
}
const currentGroup = computed(() => cityData.value[active.value])

watch([active, currentGroup], ([newActive, newCurrentGroup], [oldActive, oldCurrentGroup]) => {
  console.log('active changed:', newActive, oldActive)
  console.log('currentGroup changed:', newCurrentGroup, oldCurrentGroup)
})
</script>

<style lang="scss" scoped>
.container {
  display: flex;
  flex-direction: column;
  height: 100vh; // 确保容器占据整个视口高度

  .top {
    flex-shrink: 0; // 确保顶部部分不会收缩
    z-index: 9;
  }

  .content {
    flex-grow: 1; // 让内容部分占据剩余空间
    overflow-y: auto; // 使内容部分可滚动
    background-color: #fff; // 可选：为内容部分添加背景颜色以便区分
  }
}
</style>
